package com.platform.module.dao.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Slf4j
@Component
public class MyBatisPlusHandler implements MetaObjectHandler {

    /**
     * 创建时自动插入
     * 拦截添加了这个注解的  @TableField(fill = FieldFill.INSERT) //标识插入时自动更新
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("star insert fill....");

        // 有的表的创建是时间是ccreateTime，有的是createTime，这里做兼容
        this.strictInsertFill(metaObject, "ccreateTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "cupdateTime", LocalDateTime.class, LocalDateTime.now());
        log.info("end insert fill....");
    }

    /**
     * 更新时自动插入
     * 拦截添加了这个注解的  `@TableField(fill = FieldFill.INSERT)`
     * `@TableField(fill = FieldFill.INSERT_UPDATE)` //标识插入时自动更新
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("star update fill....");
        this.setFieldValByName("cupdateTime", LocalDateTime.now(),metaObject);
        log.info("end update fill....");
    }
}
